package view;



import dao.OrderDAO;
import dao.OrderDetailDAO;
import dao.ProductDAO;
import model.Order;
import model.OrderDetail;
import model.Product;
import model.User;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 订单列表界面类，展示订单列表及详情
 */
public class OrderListFrame extends JFrame {
    private User currentUser;          // 当前登录用户
    private OrderDAO orderDAO;         // 订单数据访问对象
    private OrderDetailDAO orderDetailDAO; // 订单详情数据访问对象
    private ProductDAO productDAO;     // 商品数据访问对象
    private JTable orderTable;         // 订单表格
    private DefaultTableModel orderTableModel; // 订单表格模型
    private JTable orderDetailTable;   // 订单详情表格
    private DefaultTableModel orderDetailTableModel; // 订单详情表格模型
    private JButton backButton;        // 返回按钮

    /**
     * 构造方法，初始化订单列表界面
     * @param user 当前登录用户
     * @param orderDAO 订单数据访问对象
     */
    public OrderListFrame(User user, OrderDAO orderDAO) {
        currentUser = user;
        this.orderDAO = orderDAO;
        orderDetailDAO = new OrderDetailDAO();
        productDAO = new ProductDAO();

        // 设置窗口标题和大小
        setTitle("在线购物系统 - 订单列表");
        setSize(900, 600);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLocationRelativeTo(null);

        // 创建面板并设置布局
        JPanel panel = new JPanel();
        panel.setLayout(new BorderLayout());
        panel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));

        // 创建订单表格模型
        orderTableModel = new DefaultTableModel();
        orderTableModel.addColumn("订单ID");
        orderTableModel.addColumn("订单日期");
        orderTableModel.addColumn("总金额");
        orderTableModel.addColumn("状态");

        // 创建订单表格并设置表格模型
        orderTable = new JTable(orderTableModel);
        orderTable.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);

        // 加载订单数据到表格
        loadOrders();

        // 创建订单滚动面板
        JScrollPane orderScrollPane = new JScrollPane(orderTable);

        // 创建订单详情面板
        JPanel orderDetailPanel = new JPanel();
        orderDetailPanel.setLayout(new BorderLayout());

        // 创建订单详情表格模型
        orderDetailTableModel = new DefaultTableModel();
        orderDetailTableModel.addColumn("订单详情ID");
        orderDetailTableModel.addColumn("商品ID");
        orderDetailTableModel.addColumn("商品名称");
        orderDetailTableModel.addColumn("价格");
        orderDetailTableModel.addColumn("数量");

        // 创建订单详情表格并设置表格模型
        orderDetailTable = new JTable(orderDetailTableModel);
        orderDetailTable.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);

        // 创建订单详情滚动面板
        JScrollPane orderDetailScrollPane = new JScrollPane(orderDetailTable);

        // 创建订单详情标题标签
        JLabel orderDetailTitleLabel = new JLabel("订单详情");
        orderDetailTitleLabel.setHorizontalAlignment(SwingConstants.CENTER);
        orderDetailTitleLabel.setFont(new Font("Arial", Font.BOLD, 16));

        // 将订单详情标题标签和滚动面板添加到订单详情面板
        orderDetailPanel.add(orderDetailTitleLabel, BorderLayout.NORTH);
        orderDetailPanel.add(orderDetailScrollPane, BorderLayout.CENTER);

        // 添加订单表格行选择监听器
        orderTable.getSelectionModel().addListSelectionListener(e -> {
            if (!e.getValueIsAdjusting()) {
                int selectedRow = orderTable.getSelectedRow();
                if (selectedRow != -1) {
                    int orderId = (Integer) orderTable.getValueAt(selectedRow, 0);
                    loadOrderDetails(orderId);
                }
            }
        });

        // 创建返回按钮并添加事件监听器
        backButton = new JButton("返回");
        backButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                // 关闭订单列表界面，返回主界面
                dispose();
                new MainFrame(currentUser).setVisible(true);
            }
        });

        // 创建按钮面板并添加返回按钮
        JPanel buttonPanel = new JPanel();
        buttonPanel.add(backButton);

        // 将订单滚动面板、订单详情面板和按钮面板添加到面板
        panel.add(orderScrollPane, BorderLayout.NORTH);
        panel.add(orderDetailPanel, BorderLayout.CENTER);
        panel.add(buttonPanel, BorderLayout.SOUTH);

        // 将面板添加到窗口
        add(panel);

        // 显示订单列表界面
        setVisible(true);
    }

    /**
     * 加载订单数据到表格
     */
    private void loadOrders() {
        // 清空表格
        orderTableModel.setRowCount(0);

        // 获取当前用户的所有订单
        List<Order> orders = orderDAO.getOrdersByUserId(currentUser.getUserId());

        // 将订单数据添加到表格
        for (Order order : orders) {
            Object[] row = {
                    order.getOrderId(),
                    order.getOrderDate(),
                    order.getTotalPrice(),
                    order.getStatus()
            };
            orderTableModel.addRow(row);
        }
    }

    /**
     * 根据订单 ID 加载订单详情数据到表格
     * @param orderId 订单 ID
     */
    private void loadOrderDetails(int orderId) {
        // 清空表格
        orderDetailTableModel.setRowCount(0);

        // 获取订单详情
        List<OrderDetail> orderDetails = orderDetailDAO.getOrderDetailsByOrderId(orderId);

        // 获取订单详情对应的商品信息
        for (OrderDetail orderDetail : orderDetails) {
            Product product = productDAO.getProductById(orderDetail.getProductId());
            if (product != null) {
                Object[] row = {
                        orderDetail.getOrderDetailId(),
                        orderDetail.getProductId(),
                        product.getProductName(),
                        product.getPrice(),
                        orderDetail.getQuantity()
                };
                orderDetailTableModel.addRow(row);
            }
        }
    }
}
